﻿using System;
using System.Threading;
using System.Windows;
using SharedServiceLibrary;

namespace Central
{
    public partial class PumpStationWindow
    {
        private readonly PumpStation _station;
        private readonly IPumpStationService _proxy;
        private readonly Window _parent;
        private Thread _thread;
        private bool _running;

        public PumpStationWindow(PumpStation station, Window parent, IPumpStationService proxy)
        {
            InitializeComponent();

            Title = station.Name + "[" + station.IPAddress + ":" + station.Port + "]";

            _parent = parent;
            _station = station;
            _proxy = proxy;

            TextBlockWaterLevel.DataContext = station;

            var pumps = proxy.GetPumps();
            for (int i = 0; i < pumps.Length; i++)
            {
                var pump = pumps[i];

                var ucp = new UcPump(i, pump);
                ucp.StartPump += UcpOnStartPump;
                ucp.StopPump += UcpOnStopPump;

                StackPanelPumps.Children.Add(ucp);
            }

            Start();
        }

        private void UcpOnStartPump(int pumpIndex)
        {
            _proxy.StartPump(pumpIndex);
        }

        private void UcpOnStopPump(int pumpIndex)
        {
            _proxy.StopPump(pumpIndex);
        }

        private void Start()
        {
            _running = true;
            _thread = new Thread(Run);
            _thread.Start();
        }

        private void Stop()
        {
            _running = false;
        }

        private void Run()
        {
            while (_running)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    var pumps = _proxy.GetPumps();
                    for (var i = 0; i < StackPanelPumps.Children.Count; i++)
                    {
                        ((UcPump) StackPanelPumps.Children[i]).Pump = pumps[i];
                    }
                }));
                Thread.Sleep(1000);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Stop();
            _parent.Show();
        }
    }
}
